package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/*
@date 2022年07月30日19:45
*/
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private  DishFlavorService dishFlavorService;


    @Override
    @Transactional
    /**
     * 菜品新增
     */
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品的信息
        save(dishDto);
        //2.保存口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        //3.菜品id
        Long dishId = dishDto.getId();
        //4.遍历给每个口味设置菜品的id
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        //5.批量保存
        dishFlavorService.saveBatch(flavors);


    }

    @Override
    /**
     * 查询菜品回显
     */
    public DishDto getByIdWithFlavor(Long id) {
        //1.查询菜品的基本信息 dish表
        Dish dish = getById(id);
        //2.查询菜品的口味信息 dishflavorbiao
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors= dishFlavorService.list(lqw);
        //3.封装到dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品的基本信息
        updateById(dishDto);
        //删除当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        //添加口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(item->item.setDishId(dishDto.getId()));
         //批量保存
        dishFlavorService.saveBatch(flavors);
    }
}
